package com.ruoyi.web.controller.Notify;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.fjzt.domain.TbFjglFjzt1;
import com.ruoyi.fjzt.service.ITbFjglFjzt1Service;
import com.ruoyi.notify.domin.RoomMessage;
import com.ruoyi.sbgl.domain.TbSbglSjcj;
import com.ruoyi.sbgl.service.ITbSbglSjcjService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Anonymous
@RestController
public class NotifyController {
    @Autowired
    private ITbSbglSjcjService tbSbglSjcjService;
    @Autowired
    private ITbFjglFjzt1Service iTbFjglFjzt1Service;
    @RequestMapping("/notifykt")
    public String notifyfz(TbFjglFjzt1 w) {

        w.setFjzt("0");
       int num= iTbFjglFjzt1Service.insertTbFjglFjzt1(w);
        System.out.println(num);
        return "SUCCESS";
    }
    @RequestMapping("/test")
    public String notifytest(RoomMessage w) {
        System.out.println("测试！！！！");
        System.out.println(w);

        return "SUCCESS";
    }
    @RequestMapping("/notify")
    public String notify(String response_content, String timestamp, String sign) {
        System.out.println("timestamp: " + timestamp);
        System.out.println("response_content: " + response_content);
        System.out.println("sign: " + sign);


        // 验签
        if(!checkSign(response_content, timestamp, sign)) {
            System.out.println("sign check failed");
            return "sign check failed";
        }
        System.out.println("sign check success");

        List<Map<String, Object>> responseContent= new ArrayList<>();
        JSONArray contentArray = JSON.parseArray(response_content);
        for(int i = 0; i < contentArray.size(); ++i) {
            HashMap<String, Object> contentMap = new HashMap<>();
            JSONObject contentObject = contentArray.getJSONObject(i);
            Set<String> keySet = contentObject.keySet();
            for(String key: keySet) {
                contentMap.put(key, contentObject.getObject(key, Object.class));
                System.out.println(key + ": " + contentObject.get(key));
            }
            responseContent.add(contentMap);
        }

        System.out.println("接收异步通知数据：" + responseContent);
        //获取总用量
        Map<String,Object>  firstData=responseContent.get(0);
        List<Map<String,Object>>  innerData=(List<Map<String,Object>>)firstData.get("data");
        Map<String,Object>  innerMap=innerData.get(0);

        List<String> valueList=(List<String>)innerMap.get("value");
        String value=valueList.get(0);
        String[] parts = value.split("\\|");


        TbSbglSjcj data=new TbSbglSjcj();
        data.setZyl(Double.parseDouble(parts[0]));
        data.setCjqbh("68102309042827");
        data.setSbbh("68102309042827");

        //获取累计正向流量
        String dsp = (String) innerMap.get("dsp");

        Pattern pattern = Pattern.compile("累计正向流量:([\\d.]+)");
        Matcher matcher = pattern.matcher(dsp);

        if (matcher.find()) {
            String accumulatedFlow = matcher.group(1);
            data.setZxll(Double.parseDouble(accumulatedFlow));
            System.out.println(Double.parseDouble(accumulatedFlow));
        }

        //获取阀门状态
        String[] parts1=dsp.split("\\s+");

        for(String part:parts1)
        {

             if(part.startsWith("阀门状态:")) {
                String state=part.substring("阀门状态:".length());
                if(state.equals("Off"))
                {
                    data.setFmzt(1L);
                }
                else if(state.equals("On"))
                {
                    data.setFmzt(0L);
                }
            }

        }

        int num=tbSbglSjcjService.insertTbSbglSjcj(data);
        System.out.println(num);

        //数据录入
        //-----------加入业务逻辑-----------
        //--------------------------------

        return "SUCCESS";
    }
    @RequestMapping("/notifykai")
    public String notifykai(String response_content, String timestamp, String sign) {
        System.out.println("timestamp: " + timestamp);
        System.out.println("response_content: " + response_content);
        System.out.println("sign: " + sign);


        // 验签
        if(!checkSign(response_content, timestamp, sign)) {
            System.out.println("sign check failed");
            return "sign check failed";
        }
        System.out.println("sign check success");

        List<Map<String, Object>> responseContent= new ArrayList<>();
        JSONArray contentArray = JSON.parseArray(response_content);
        for(int i = 0; i < contentArray.size(); ++i) {
            HashMap<String, Object> contentMap = new HashMap<>();
            JSONObject contentObject = contentArray.getJSONObject(i);
            Set<String> keySet = contentObject.keySet();
            for(String key: keySet) {
                contentMap.put(key, contentObject.getObject(key, Object.class));
            }
            responseContent.add(contentMap);
        }

        System.out.println("接收异步通知数据：" + responseContent);
        //-----------加入业务逻辑-----------
        //--------------------------------

        return "SUCCESS";
    }
    @RequestMapping("/notifguan")
    public String notifyguan(String response_content, String timestamp, String sign) {
        System.out.println("timestamp: " + timestamp);
        System.out.println("response_content: " + response_content);
        System.out.println("sign: " + sign);


        // 验签
        if(!checkSign(response_content, timestamp, sign)) {
            System.out.println("sign check failed");
            return "sign check failed";
        }
        System.out.println("sign check success");

        List<Map<String, Object>> responseContent= new ArrayList<>();
        JSONArray contentArray = JSON.parseArray(response_content);
        for(int i = 0; i < contentArray.size(); ++i) {
            HashMap<String, Object> contentMap = new HashMap<>();
            JSONObject contentObject = contentArray.getJSONObject(i);
            Set<String> keySet = contentObject.keySet();
            for(String key: keySet) {
                contentMap.put(key, contentObject.getObject(key, Object.class));
            }
            responseContent.add(contentMap);
        }

        System.out.println("接收异步通知数据：" + responseContent);
        //-----------加入业务逻辑-----------
        //--------------------------------

        return "SUCCESS";
    }
    private boolean checkSign(String response_content, String timestamp, String sign) {
        // 随机字符串 后台获取
        String nonce = "yDc1ZtZfU6FmsiWm1Ms63KA1";
        String buf = response_content + timestamp + nonce;
        String encode = getMD5(buf);
        return encode.equals(sign);
    }

    // md5加密
    private String getMD5(String password) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        byte[] byteArray = password.getBytes(StandardCharsets.UTF_8);

        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }

            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }


}
